package controller

import (
	"fmt"
	"github.com/gin-gonic/gin"
	"github.com/gin-gonic/gin/binding"
	"github.com/go-gin-admin/model"
	"github.com/go-gin-admin/util"
	"net/http"
	"time"
)

// 添加字典
func AddDict(c *gin.Context) {
	var dictData model.Dict

	if err := c.BindWith(&dictData, binding.JSON); err != nil {
		c.JSON(http.StatusOK, new(util.Response).Err("参数解析错误"))
		return
	}
	local := time.Now().Local()
	dictData.CreateTime = local
	dictData.UpdateTime = local
	// 调用service
	insertId, err := dictData.Insert()
	if err != nil {
		c.JSON(http.StatusOK, new(util.Response).Err("新建失败"))
		return
	}
	m := make(map[string]interface{})
	m["insertId"] = insertId
	c.JSON(http.StatusOK, new(util.Response).Ok("创建成功", m))
}

// 获取字典
func GetDict(c *gin.Context) {
	// 获取参数
	pageSize, _ := util.StringToInt64(c.DefaultQuery("pageSize", "10"))
	pageIndex, _ := util.StringToInt64(c.DefaultQuery("pageIndex", "1"))
	var dictData model.Dict
	data, err := dictData.GetList(pageIndex, pageSize)
	if err != nil {
		c.JSON(http.StatusOK, new(util.Response).Err("获取字典失败"))
		return
	}
	c.JSON(http.StatusOK, new(util.Response).Ok("获取成功", data))

	fmt.Println(pageSize, pageIndex)
}

// 更新字典
func UpdateDict(c *gin.Context) {
	var dictData model.Dict
	if err := c.BindWith(&dictData, binding.JSON); err != nil {
		c.JSON(http.StatusOK, new(util.Response).Err("参数解析错误"))
		return
	}
	dictData.UpdateTime = time.Now().Local()
	if err := dictData.Update(); err != nil {
		c.JSON(http.StatusOK, new(util.Response).Err("修改失败"))
	}
	c.JSON(http.StatusOK, new(util.Response).Ok("修改成功", nil))
}

// 删除字典
func RemoveDict(c *gin.Context) {
	var dictData model.Dict
	// 获取id
	id, _ := util.StringToInt64(c.Param("id"))
	if err := dictData.Remove(id); err != nil {
		c.JSON(http.StatusOK, new(util.Response).Err("删除失败"))
	}
	c.JSON(http.StatusOK, new(util.Response).Ok("删除成功", nil))
}
